package com.weixin.gong.example.serializer;

import java.io.*;

/**
 * @author weixin.gong
 * @date 15-7-6 下午4:54
 */
public class JavaSerializer<T> {

    public T fromBytes(byte[] bits) throws IOException {
        if(bits == null || bits.length == 0)
            return null;
        ObjectInputStream ois = null;
        try {
            ByteArrayInputStream bais = new ByteArrayInputStream(bits);
            ois = new ObjectInputStream(bais);
            //noinspection unchecked
            return (T)ois.readObject();
        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        } finally {
            if(ois != null)
                try {
                    ois.close();
                } catch (IOException ignored) {}
        }
    }

    public byte[] toBytes(T var)  throws IOException {
        ObjectOutputStream oos = null;
        try {
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            oos = new ObjectOutputStream(baos);
            oos.writeObject(var);
            return baos.toByteArray();
        } finally {
            if(oos != null) {
                try {
                    oos.close();
                } catch (IOException ignored) {}
            }
        }
    }



    public static void main(String[] args) throws IOException {
        TestObject test = new TestObject(1, 1L);
        System.out.println(test);
        byte[] bytes = new JavaSerializer<TestObject>().toBytes(test);
        System.out.println(new JavaSerializer<TestObject>().fromBytes(bytes));
    }

    static class TestObject {
        private int i;
        private Long l;

        public TestObject(int i, Long l) {
            this.i = i;
            this.l = l;
        }

        @Override public String toString() {
            return "TestObject{" +
                    "i=" + i +
                    ", l=" + l +
                    '}';
        }
    }
}
